<?php
class Register extends Controller{
    public $data;
    function __construct(){
        parent::__construct();
        Session::init();
        $this->bar = new Bar();
        $this->model("model_website");
    }

    public function index(){
        if (Session::get("uid") > 0){
            header('location:' . ROOT_URL);
        }else{
            $province = $this->model_website->getProvince();
            $salaries = $this->model_website->getSalary();
            //add user
            if(!empty($_POST)){
                $username = $_POST['username'];
                $password = md5($_POST['password']);
                $email =  $_POST['email'];
                $pid = $_POST['pid'];
                $sex = 0;
                if(isset($_POST['sex'])){
                    $sex = $_POST['sex'];
                }
                $salary = $_POST['salary'];
                $children = 0;
                if($_POST['children']){
                    $children = $_POST['children'];
                }
                $data = $this->model_website->addUser($username, $password, $email, $pid, $sex, "", $salary, $children);

                Session::set("uid", $data[0]);
                Session::commit();
                if(Session::get("url")){
                    header('location:' . ROOT_URL.Session::get("url"));
                }else{
                    header('location:' . ROOT_URL);
                }
            }

            $this->data['province'] = $province;
            $this->data['salary'] = $salaries;
            $this->data['month'] = $this->getMonth();

        }

        //Bar content
        $bar_content = $this->bar->getBarRegister();
        $this->data['bar_content'] = $bar_content;
        $this->data['view'] = "register";
        $this->data['type'] = "user";
        $this->data['title'] = "Tạo tài khoản buzzer";
        $this->data['data'] = "";
        $this->view->render("layout/body", $this->data);
    }

    public function checkUsername(){
        if(isset($_POST['username'])){
            $username = $_POST['username'];
            $data = $this->model_website->getUserByUsername($username);
            if($data){
                echo json_encode(array("status"=>"error"));
            }else{
                echo json_encode(array("status"=>"ok"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function checkEmail(){
        if(isset($_POST['email'])){
            $email = $_POST['email'];
            $data = $this->model_website->getUserByEmail($email);
            if($data){
                echo json_encode(array("status"=>"error"));
            }else{
                echo json_encode(array("status"=>"ok"));
            }

        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function signUpFacebookUrl(){
        $config = array();

        require_once ROOT_PATH . '/views/platform/facebook/src/config.php';
        require_once ROOT_PATH . '/views/platform/facebook/src/facebook.php';
        $facebook = new Facebook(array(
            'appId' => $config['App_ID'],
            'secret' => $config['App_Secret'],
            'cookie' => true
        ));
        $config['callback_url'] = ROOT_URL."register/signUpFacebook?fbTrue=true";
        $url = 'https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,public_profile,publish_stream';

        echo json_encode(array("status"=>"ok", "url"=>$url));
    }

    public function signUpFacebook(){
        //facebook api
        $config = array();
        require ROOT_PATH . '/views/platform/facebook/src/config.php';
        require ROOT_PATH . '/views/platform/facebook/src/facebook.php';
        $facebook = new Facebook(array(
            'appId' => $config['App_ID'],
            'secret' => $config['App_Secret'],
            'cookie' => true
        ));

        $config['callback_url'] = ROOT_URL."register/signUpFacebook?fbTrue=true";
        if (isset($_GET['fbTrue'])) {
            $token_url = "https://graph.facebook.com/oauth/access_token?"
                . "client_id=" . $config['App_ID'] . "&redirect_uri=" . urlencode($config['callback_url'])
                . "&client_secret=" . $config['App_Secret'] . "&code=" . $_GET['code'];

            $response = file_get_contents($token_url);
            $params = null;
            parse_str($response, $params);

            $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
            $fb_user = json_decode(file_get_contents($graph_url, true));

            $fb_id = $fb_user->id;
            $fb_token = $params['access_token'];

            $user = $this->model_website->getUserByFacebookId($fb_id);
            if($user){
                //set cookie and refresh page
                $uid = $user[0]['uid'];
                Session::set("uid", $uid);
                Session::commit();
            }else{
                //create new user
                $email = $fb_user->email;
                $first_name = $fb_user->first_name;
                $last_name = $fb_user->last_name;
                $gender = $fb_user->gender;
                $sex = "0";;
                if($gender == "male"){
                    $sex = "0";
                }else{
                    $sex = "1";
                }
                $birthday = $fb_user->birthday;
                $datetime = new DateTime($birthday);
                $birthday = $datetime->format('Y-m-d');

                $date = date('Y-m-d H:i:s');
                $uid = $this->model_website->addUserByFacebook($first_name, $last_name, $email, $sex, $birthday, $date, $fb_id, $fb_token);
                if($uid){
                    Session::set("uid", $uid);
                    Session::commit();
                }
            }
            echo "<script>window.close(); </script>";
        }
    }

    public function getMonth(){
        $arrMonth = array(
            "1" => "Jan",
            "2" => "Feb",
            "3" => "Mar",
            "4" => "Apr",
            "5" => "May",
            "6" => "Jun",
            "7" => "Jul",
            "8" => "Aug",
            "9" => "Sep",
            "10" => "Oct",
            "11" => "Nov",
            "12" => "Dec",
        );

        return $arrMonth;
    }
}
?>